<!--
 * Copyright © 2023
 * @Author: zhangxiang
 * @Date: 2023-06-05 17:48:02
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-09-21 15:27:32
 * @Description:
 *
-->

<template>
  <el-dialog
    class="add-normal-rule-dialog"
    :title="!isEdit ? '添加普通告警规则' : '编辑告警规则'"
    :visible="show"
    width="700px"
    top="15vh"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="closeClick"
  >
    <el-form ref="addForm" :rules="rules" :model="form" label-width="auto">
      <el-form-item label="告警名称" prop="ruleName">
        <el-input
          v-model="form.ruleName"
          :disabled="isEdit"
          placeholder="请输入告警名称"
        />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="模板" prop="ruleTemplate">
        <el-select
          v-model="ruleTemplate"
          placeholder="请选择合适的规则模板"
          style="width: 100%"
          @change="ruleTemplateChange"
        >
          <el-option
            v-for="item in ruleTemplateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="规则表达式" prop="ruleExp">
        <el-input
          v-model="form.ruleExp"
          placeholder="请输入规则表达式"
          type="textarea"
          :rows="2"
        />
        <div class="item-hint">
          <i class="el-icon-info icon"></i>
          <div class="text">请输入PromQL表达式</div>
        </div>
      </el-form-item>
      <el-form-item label="持续时间" prop="duration">
        <el-input-number
          v-model="form.duration"
          style="width: 150px"
          :min="1"
          label="持续时间"
        />
        <span style="margin-left: 10px">{{
          form.duration > 1 ? "mins" : "min"
        }}</span>
        <div class="item-hint">
          <i class="el-icon-info icon"></i>
          <div class="text">
            默认设置为5，表示在5分钟内设置的监控指标持续到达设置阈值条件，则触发告警
          </div>
        </div>
      </el-form-item>
      <el-form-item label="告警级别" prop="alarmLevel">
        <el-radio-group v-model="form.alarmLevel">
          <el-radio
            v-for="item in levelOptions"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="cancelClick">取 消</el-button>
      <el-button
        type="primary"
        size="small"
        :loading="confirmLoading"
        @click="confirmClick"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRule, updateRule } from '@/api/cnap/statis-analysis'
import { ALARM_LEVEL } from '@/utils/cnap/constant'

// 默认form
const getDefaultForm = () => {
  return {
    ruleName: '', // 告警名称
    ruleExp: '', // 规则表达式
    duration: 5, // 持续时间
    alarmLevel: '' // 告警级别
  }
}

export default {
  name: 'AddNormalDialog',
  components: {},
  props: {
    // 是否显示
    show: {
      type: Boolean,
      default: false
    },
    // 是否编辑
    isEdit: {
      type: Boolean,
      default: false
    },
    // 应用信息
    info: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      ruleTemplate: 'no',
      ruleTemplateOptions: [
        {
          label: '无',
          value: 'no',
          rule: ''
        },
        {
          label: '节点CPU使用率超80%',
          value: 'node_cpu_above_80',
          rule: '100 - (avg by(node, cluster_name, cluster) (rate(node_cpu_seconds_total{mode="idle"}[2m])) * 100) > 80'
        },
        {
          label: '节点内存可用率不足10%',
          value: 'node_memory_under_10',
          rule: 'node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100 < 10'
        },
        {
          label: '集群CPU使用率超80%',
          value: 'cluster_cpu_above_80',
          rule: '100 - (avg by(cluster_name, cluster) (rate(node_cpu_seconds_total{mode="idle"}[2m])) * 100) > 80'
        },
        {
          label: '集群内存使用率超80%',
          value: 'cluster_memory_under_10',
          rule: '(1-sum(node_memory_MemAvailable_bytes)by(cluster_name, cluster)/sum(node_memory_MemTotal_bytes)by(cluster_name, cluster))*100 > 80'
        }
      ],
      levelOptions: ALARM_LEVEL, // 级别选项
      // 校验规则
      rules: {
        // 告警名称
        ruleName: [
          { required: true, message: '请输入告警名称', trigger: 'blur' }
        ],
        // 规则表达式
        ruleExp: [
          { required: true, message: '请输入规则表达式', trigger: 'blur' }
        ],
        // 持续时间
        duration: [
          { required: true, message: '请输入持续时间', trigger: 'blur' },
          { pattern: /^([0-9]*)$/, message: '请输入整数' }
        ],
        // 告警级别
        alarmLevel: [
          { required: true, message: '请选择告警级别', trigger: 'blur' }
        ]
      },
      form: getDefaultForm(), // 表单
      confirmLoading: false
    }
  },
  computed: {},
  watch: {
    /**
     * @description: 监听是否编辑
     * @return {*}
     */
    isEdit: {
      handler(newVal) {
        if (newVal) {
          // 初始化数据
          this.form = this.info
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    /**
     * @description: 模板变化
     * @param {*} val
     * @return {*}
     */
    ruleTemplateChange(val) {
      const findTemplate = this.ruleTemplateOptions.find(item => {
        return item.value === val
      })
      if (findTemplate) {
        this.form.ruleExp = findTemplate.rule
      }
    },
    /**
     * @description: 确定
     * @return {*}
     */
    confirmClick() {
      // 校验
      this.$refs.addForm.validate((valid, obj) => {
        if (valid) {
          // 合法
          this.confirmLoading = true
          if (!this.isEdit) {
            // 添加规则
            // 请求接口
            addRule({
              ...this.form
            })
              .then((res) => {
                this.closeClick()
                this.$emit('add-success')
              })
              .finally(() => {
                this.confirmLoading = false
              })
          } else {
            // 编辑
            // 请求接口
            updateRule({
              ...this.form
            })
              .then((res) => {
                this.closeClick()
                this.$emit('edit-success')
              })
              .finally(() => {
                this.confirmLoading = false
              })
          }
        }
      })
    },
    /**
     * @description: 关闭
     * @return {*}
     */
    closeClick() {
      this.$emit('update:show', false)
    },
    /**
     * @description: 取消
     * @return {*}
     */
    cancelClick() {
      this.closeClick()
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.add-normal-rule-dialog {
  .item-hint {
    margin-top: 5px;
    display: flex;
    align-items: center;
    .icon {
      font-size: 14px;
      color: #c3c3c3;
      margin-right: 5px;
    }
    .text {
      .textStyle(14px , 400, #C3C3C3);
      line-height: 20px;
    }
  }
  /deep/ .el-radio {
    margin-right: 25px;
  }
}
</style>
